
#import "EGAAppDelegate.h"
#import "EGAEmployeeInfo.h"
#import "EGAAbsentTypeCellInfo.h"
#import "EGAViewController.h"
#import "mainEGAViewController.h"

NSString *serviceUrl=@"164.115.5.192/Archive/ArchivesServiceiOS/";

@implementation EGAAppDelegate

@synthesize dateFormat;
@synthesize absentTypeCellInfoMasterArray;
@synthesize employeeInfo;



#define dateFotmatUpdateFull @"อัพเดทล่าสุด d MMM yyyy HH:mm  น."
#define dateFotmatThaiDateFull @"d MMM yyyy HH:mm น."
#define dateFotmatThaiMonthFull @"MMMM"
#define dateFotmatThaiYear @"yyyy"
#define dateFotmatEngDateFull @"d MMM yyyy HH:mm"
#define dateFotmatDate @"d MMM yyyy"

#pragma mark - userInfo management

#define employeeInfoJSON @"employeeInfoJSON"

#define absentInfoJSON @"absentInfoJSON"
#define updateAbsentDateStringKey  @"updateAbsentDateStringKey"

#define absentPendingInfoJSON @"absentPendingInfoJSON"
#define updateAbsentPendingDateStringKey  @"updateAbsentPendingDateStringKey"

#define holidayInfoJSON @"holidayInfoJSON"
#define updateHolidayDateStringKey  @"updateHolidayDateStringKey"

 

#define absentDateInfoJSON @"absentDateInfoJSON"
#define updateAbsentDateDateStringKey  @"updateAbsentDateDateStringKey"

#define jsonAbsentTypeTotalUsageUnit @"TotalUsageUnit"
#define jsonAbsentTypeID @"AbsentTypeID"
#define jsonAbsentTypeRate @"Rate"
-(NSDateFormatter *)dateFormatWithUpdateStringFormat
{
    if (!dateFormat) {
        dateFormat = [[NSDateFormatter alloc] init];
    }
    NSLocale * locale = [[NSLocale alloc] initWithLocaleIdentifier:@"th_TH"];
    [dateFormat setLocale:locale];
    [dateFormat setDateFormat:dateFotmatUpdateFull];
    return dateFormat;
}


//
//-(NSString*)getDateTh:(NSString*)strDate
//{
//   
//    NSString *str = strDate;
//    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
//    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
//    NSDate *date = [dateFormatter dateFromString: str];
//    
//    dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
//    [dateFormatter setDateFormat:@"dd/MM/yyyy"];
//    NSString *convertedString = [dateFormatter stringFromDate:date];
//    
//    
//    NSDate *now = date;
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyy"];
//    NSString *year = [formatter stringFromDate:now];
//    [formatter setDateFormat:@"MM"];
//    NSString *month = [formatter stringFromDate:now];
//    [formatter setDateFormat:@"dd"];
//    NSString *day = [formatter stringFromDate:now];
//    NSString *yearString = year;
//    int yearInt = [yearString intValue];
//    int dayInt = [day intValue];
//    if (dayInt < 10) {day=[NSString stringWithFormat:@"%d",dayInt];  }
//    if (yearInt<2500)
//    {
//        yearInt=yearInt+543;
//        year=[NSString stringWithFormat:@"%d",yearInt];
//    }
//    
//    NSString *monthString=@"";
//    if ([month isEqualToString:@"01"]) {
//        monthString = @"ม.ค.";
//    }
//    else  if ([month isEqualToString:@"02"]) {
//        monthString = @"ก.พ.";
//    }
//    else  if ([month isEqualToString:@"03"]) {
//        monthString = @"มี.ค.";
//    }
//    else  if ([month isEqualToString:@"04"]) {
//        monthString = @"เม.ย.";
//    }
//    else  if ([month isEqualToString:@"05"]) {
//        monthString = @"พ.ค.";
//    }
//    else  if ([month isEqualToString:@"06"]) {
//        monthString = @"มิ.ย.";
//    }
//    else  if ([month isEqualToString:@"07"]) {
//        monthString = @"ก.ค.";
//    }
//    else  if ([month isEqualToString:@"08"]) {
//        monthString = @"ส.ค.";
//    }
//    else  if ([month isEqualToString:@"09"]) {
//        monthString = @"ก.ย.";
//    }
//    else  if ([month isEqualToString:@"10"]) {
//        monthString = @"ต.ค.";
//    }
//    else  if ([month isEqualToString:@"11"]) {
//        monthString = @"พ.ย.";
//    }
//    else  if ([month isEqualToString:@"12"]) {
//        monthString = @"ธ.ค.";
//    }
//    
//    convertedString=[NSString stringWithFormat:@"%1@ %1@ %3@ ",day,monthString,year];
//    return convertedString;
//}

-(void)fetchAbsentInfo:(NSArray*)infoArray
{
    NSMutableArray *tmpArray = [NSMutableArray arrayWithArray:[self absentTypeCellInfoMasterArray]];
    
    for (NSDictionary * absentInfoDic in infoArray) {
        NSInteger typeID= [self getJSONInt:[absentInfoDic objectForKey:jsonAbsentTypeID]];
        NSInteger usageUnit= [self getJSONInt:[absentInfoDic objectForKey:jsonAbsentTypeTotalUsageUnit]];
        NSInteger rate= [self getJSONInt:[absentInfoDic objectForKey:jsonAbsentTypeRate]];
        for (EGAAbsentTypeCellInfo* absentInfo in tmpArray) {
            if (absentInfo.absentTypeID == typeID) {
                [absentInfo setTimeUnit:usageUnit withRate:rate];
                break;
            }
        }
    }
    
    self.absentTypeCellInfoMasterArray = [NSMutableArray arrayWithArray:tmpArray];
    
    tmpArray = nil;
}

-(EGAEmployeeInfo*)getCurrentEmpInfo
{
    return self.employeeInfo;
}


-(void)saveEmployeeInfoJSON:(NSString*)json
{
    [[self userInfo] setValue:json forKey:employeeInfoJSON];
    [[self userInfo] synchronize];
    
}

- (void)dealloc
{
//    [_window release];
//    [_viewController release];
    [super dealloc];
}

-(NSUserDefaults*)userInfo
{
    if (!userInfo) {
        userInfo = [NSUserDefaults standardUserDefaults];
    }
    return userInfo;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    //self.viewController = [[mainEGAViewController alloc] initWithNibName:@"mainEGAViewController" bundle:nil];
    self.viewController = [[EGAViewController alloc] initWithNibName:@"EGAViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    
   [self initDocumentsDirectory];
    return YES;
}

-(void)saveAbsentTypeInfoJSON:(NSString*)json
{
    [[self userInfo] setValue:json forKey:absentInfoJSON];
    [[self userInfo] synchronize];
    
    [self saveAbsentLastUpdateDate:[[self dateFormatWithUpdateStringFormat] stringFromDate:[NSDate date]]];
}

-(void)saveAbsentLastUpdateDate:(NSString*)dateString
{
    [[self userInfo]setValue:dateString forKey:updateAbsentDateStringKey];
}


- (BOOL) connectedToInternet
{
    /*
     NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.ega.or.th"]];
     return ( URLString != NULL ) ? YES : NO;*/
    return YES;
    
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
-(NSInteger)getJSONInt:(NSObject*)obj
{
    return [(NSNumber*)obj intValue];
}

-(Boolean)getJSONBoolean:(NSObject*)obj
{
    return ([(NSNumber*)obj intValue] == 0)?NO:YES;
}

-(NSString*)getJSONString:(NSObject*)obj
{
    return ([obj isEqual:[NSNull null]] || [[NSString stringWithFormat:@"%@", obj]isEqualToString:@"(null)"]|| [[NSString stringWithFormat:@"%@", obj]isEqualToString:@"<null>"])?@"":[NSString stringWithFormat:@"%@", obj];
}
#pragma mark - employee info

#define jsonEmpID @"EmpID"
//#define jsonEmail @"Email"
//#define jsonIsFemale @"IsFemale"
//#define jsonReligionID @"ReligionID"
//#define jsonContractStatus @"ContractStatus"
//#define jsonTitleID @"TitleID"
//#define jsonTitleName @"TitleName"
#define jsonFirstName @"FirstNameTH"
#define jsonLastName @"LastNameTH"
#define jsonSectorName @"SectorName"
#define jsonIsHeadEGA @"isHeadEGA"

#define jsonRoleID @"RoleID"
#define jsonRoleName @"RoleName"
#define jsonTitle @"Title"

-(void)fetchEmployeeInfo:(NSDictionary*)empInfo
{
    NSString *EmpID = [empInfo objectForKey:jsonEmpID];
    NSString *FirstNameTH= [empInfo objectForKey:jsonFirstName];
    NSString *LastNameTH= [empInfo objectForKey:jsonLastName];
    NSString *SectorName= [empInfo objectForKey:jsonSectorName];
    NSString *RoleID= [empInfo objectForKey:jsonRoleID];
    NSString *RoleName= [empInfo objectForKey:jsonRoleName];
    NSString *Title= [empInfo objectForKey:jsonTitle];
    BOOL IsHeadEGA= [self getJSONBoolean:[empInfo objectForKey:jsonIsHeadEGA]];
    
    
    self.employeeInfo =
    [EGAEmployeeInfo EGAEmployeeInfoWithEmpID:EmpID
     RoleID:RoleID RoleName:RoleName Title:Title FirstNameTH:FirstNameTH LastNameTH:LastNameTH SectorName:SectorName IsHeadEGA:IsHeadEGA];
                                
   
}

-(void)initDocumentsDirectory{ //หา Home Path
    NSString *home = NSHomeDirectory(); //หา Documents Path
    NSString *documents =
    [home stringByAppendingPathComponent:@"Documents"];
    //หา Bundle Path
    NSString *bundle = [[NSBundle mainBundle] bundlePath]; //สร%าง file manager object
    NSLog(@"bundle::%@",bundle);
    NSFileManager *manager = [NSFileManager defaultManager]; //อ(านรายชื่อไฟล1จาก Main Bundle
    NSArray *files = [manager contentsOfDirectoryAtPath:bundle error:nil];
    for(NSString *file in files){
        //เลือก Copy เฉพาะไฟล1นามสกุล plist , sqlite
        if(([file rangeOfString:@".plist"].length > 0) ||
           ([file rangeOfString:@".sqlite"].length > 0))
        {
            //อ(านชื่อไฟล1ต%นฉบับ จาก Bundle
            NSString *orig = [bundle stringByAppendingPathComponent:file]; //ไฟล1ปลายทางใน Documents
            NSString *dest = [documents stringByAppendingPathComponent:file]; //ตรวจสอบไฟล1ปลายทางว(ามีอยู(แล%วหรือยัง
            if(![manager fileExistsAtPath:dest])
            {
                //ถ%าไม(มีให%ทําการ Copy file ไปยัง Documents
                [manager copyItemAtPath:orig toPath:dest error:nil];
            }
        }
    }
}
@end
